import { init } from 'snabbdom/build/package/init.js'
import { classModule } from 'snabbdom/build/package/modules/class.js'
import { heroModule } from 'snabbdom/build/package/modules/hero.js'
import { styleModule } from 'snabbdom/build/package/modules/style.js'
import { attributesModule } from 'snabbdom/build/package/modules/attributes.js'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners.js'
import { h } from 'snabbdom/build/package/h.js'
const pic = require('./img/a.jpg')

var patch = init([classModule, heroModule, styleModule, eventListenersModule, attributesModule])

var vnode

var data = {
  shops: [
    {score: 80, distance: 1.2, name: '河南面馆'},
    {score: 78, distance: 2.2, name: '沙县小吃'},
    {score: 92, distance: 0.8, name: '淮南牛肉汤'},
    {score: 88, distance: 2.0, name: '兰州拉面'},
    {score: 67, distance: 0.6, name: '幸福饺子馆'},
  ],
  currentIndex: -1
}

function switchRankRule(ind) {
  data.currentIndex = ind
  if (ind === 0) {
    data.shops.sort((s1, s2) => s2.score - s1.score)
  } else if (ind === 1) {
    data.shops.sort((s1, s2) => s1.distance - s2.distance)
  }
  render()
}

function render () {
  vnode = patch(vnode, view(data))
}

const overviewView = (shops) =>
  h('div.page', {
    style: {
      width: '300px',
      margin: '0 auto',
      paddingTop: '50px'
    }
  }, [ 
    h('div.header', {style: {marginBottom: '20px'}}, [
      h('span', {style: {marginRight: '20px'}}, '排序：'),
      ...(['评分', '距离'].map((el, ind) => {
        return h('button', {
          style: {color: data.currentIndex == ind ? 'blue' : '', marginRight: '10px'},
          on: {click: [() => {switchRankRule(ind)}]}
        }, [el])
      }))
    ]),
    h('div.page-content', shops.map(shop => {
      return h('div.row', {
        style: {
          height: '50px',
          marginBottom: '10px',
          border: '1px solid #cccccc',
          padding: '10px',
          display: 'flex',
          alignItems: 'center'
        }
      }, [
        h('img', {style: {width: '50px', height: '50px', marginRight: '20px'}, attrs: {src: pic}}),
        h('div', [
          h('div.name', {style: {marginBottom: '10px'}}, shop.name),
          h('div', [
            h('span', {style: {marginRight: '20px'}}, `评分：${shop.score}`),
            h('span', `距离：${shop.distance}`)
          ])
        ])
      ])
    })),
  ])

const view = (data) =>
  h('div.page-container', [
    overviewView(data.shops)
  ])

window.addEventListener('DOMContentLoaded', () => {
  var app = document.getElementById('app')
  vnode = patch(app, view(data))
  render()
})